#!/bin/bash

echo "🔨 重新编译多模型AI系统"
echo "================================"

# 清理并重新构建
rm -rf bin .objs
mkdir -p bin .objs

# 编译设置
INCLUDES="-I../cbp2make/lib -I../cbp2make/lib/tinyxml -I../cbp2make/src -Ilib -Isrc"
CXXFLAGS="-std=c++11 -DAICODER_ENHANCED -m64"

echo "📝 编译新文件..."

# 编译新添加的AI模型文件
compile_file() {
    local file=$1
    local base=$(basename "$file" .cpp)
    echo "  编译: $base.cpp"
    g++ $INCLUDES $CXXFLAGS -c "$file" -o ".objs/$base.o" >/dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo "    ✅ 成功"
        return 0
    else
        echo "    ❌ 失败"
        # 显示详细错误
        g++ $INCLUDES $CXXFLAGS -c "$file" -o ".objs/$base.o"
        return 1
    fi
}

echo "🔸 AI 模型核心文件:"
compile_file "src/ai_model_config.cpp"
compile_file "src/unified_ai_client.cpp" 
compile_file "src/aicoder_enhancements.cpp"

echo ""
echo "🔸 cbp2make 核心文件:"
for file in ../cbp2make/src/*.cpp; do
    base=$(basename "$file" .cpp)
    if [ ! -f ".objs/$base.o" ]; then
        compile_file "$file"
    fi
done

echo ""
echo "🔸 STL 工具库:"
for file in ../cbp2make/lib/stl*.cpp; do
    base=$(basename "$file" .cpp)
    if [ ! -f ".objs/$base.o" ]; then
        compile_file "$file"
    fi
done

echo ""
echo "🔸 TinyXML 核心库:"
for file in ../cbp2make/lib/tinyxml/*.cpp; do
    base=$(basename "$file" .cpp)
    if [ "$base" != "xmltest" ] && [ ! -f ".objs/$base.o" ]; then
        compile_file "$file"
    fi
done

# 检查是否需要安装 curl
echo ""
echo "🔍 检查 cURL 依赖:"
if ! command -v curl &> /dev/null; then
    echo "⚠️  需要安装 cURL 开发库"
    echo "请运行: pacman -S curl"
    # 暂时注释掉 curl 相关代码进行测试
    echo "暂时使用模拟模式编译..."
    CXXFLAGS="$CXXFLAGS -DNO_CURL"
fi

# 链接
echo ""
echo "🔗 链接可执行文件..."
g++ -m64 .objs/*.o -o bin/cbp2make_ai

if [ -f "bin/cbp2make_ai" ]; then
    echo ""
    echo "🎉 多模型AI系统编译成功!"
    echo "📊 统计:"
    echo "   - 对象文件: $(find .objs -name "*.o" | wc -l) 个"
    echo "   - 可执行文件: bin/cbp2make_ai"
else
    echo "❌ 编译失败"
    exit 1
fi
